// Logistics/Navigator/Navigator.js
import {config} from "../../utils/config";
Page({
  data: {
    isStaff: true,
    staffName: '操作员',
  },
  //事件处理函数
  bindViewTap: function () {

  },
  onLoad: function (options) {
    let isStaff = wx.getStorageSync('isStaff')
    let staffFile = wx.getStorageSync('staffFile') || {}
    if(isStaff === '') {    // 本地存储中没有isStaff这个key
      return
    }
    this.setData({
      isStaff,
      staffName: `操作员${staffFile.yggh || ''}${staffFile.ygxm || ''}`,
    })
  },
  pageNavigator(e) {
    let url = e.currentTarget.dataset.url

    if (url === 'driver'){
      //司机登录跳转首页
      this.login().then(() =>{wx.redirectTo({url: '/Logistics/Index/Index',})})
    }
    else if(url === 'search'){
      let token = wx.getStorageSync('token');
      if (token){
        wx.navigateTo({url: '/Logistics/Waybill/Waybill'})
        return
      }
      this.login().then(() =>{wx.navigateTo({url: '/Logistics/Waybill/Waybill'})})
    }
    else {
      wx.navigateTo({url,})
    }
  },

  login(){
    return new Promise(resolve => {
      wx.login({
        success: res => {
          wx.showLoading({ mask: true, });
          let {system_id,system_type} = config
          let post = {
            code: res.code,
            system_id,
            system_type,
          }
          wx.$post(1,'Authorize/Token_miniprogram',post).then(res => {
            if (res.errcode != 0) return;
            let {miniprogram_OpenID,token,refresh_token} = res.data.row[0] || {};
            let storageObj = {
              openid: miniprogram_OpenID,
              loginType: 'noLogin',
              refresh: refresh_token,
              token,
              system_type
            };
            Object.entries(storageObj).forEach(([key, val]) => wx.setStorageSync(key, val));
            this.getUserInfo(miniprogram_OpenID);
            wx.hideLoading();
            resolve();
          })
        },
        fail: () =>{
          wx.navigateTo('/Logistics/Logins/Logins')
        }
      })
    })
  },

  //直接使用用户，获取用户信息
  getUserInfo(openid){

    let url = 'WXMiniProgram/get_miniprogram_customer_user_inf',
      post = {
        // "system_id": 0,
        // "unionid": "string",
        "miniprogram_OpenID": openid,
        // "offiaccount_OpenID": "string"
      };
    wx.$post(1,url,post).then(res => {
      if (res.errcode != 0) return;
      let data = res.data.row,
        name = data[0] && data[0].Nickname || openid;
      wx.setStorageSync('user_name',name)
    })
  },


  //切换系统到diy
  toggleSys(){
    wx.redirectTo({url: '/pages/login/login'})
  },

})
